package com.orkhonsoft.tengrinshar.chat.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.orkhonsoft.tengrinshar.chat.entity.ChatRecordEntity;
import com.orkhonsoft.tengrinshar.chat.mapper.NoticeConsume;
import com.orkhonsoft.tengrinshar.chat.mapper.UserMapper;
import com.orkhonsoft.tengrinshar.chat.service.ChatRecordService;
import com.orkhonsoft.tengrinshar.chat.utils.JpushClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint(value = "/websocket/{username}"/*,configurator = MySpringConfigurator.class*/)
public class MyWebSocket {

    @Autowired
    private UserMapper userMapper;

    private NoticeConsume noticeConsume;
    private ChatRecordService ChatRecordService;

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        MyWebSocket.applicationContext = applicationContext;
    }

    /**
     * 在线人数
     */
    public static int onlineNumber = 0;
    /**
     * 以用户的姓名为key，WebSocket为对象保存起来
     */
    private static Map<String, MyWebSocket> clients = new ConcurrentHashMap<String, MyWebSocket>();
    /**
     * 会话
     */
    private Session session;
    /**
     * 用户名称
     */
    private String username;

    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        onlineNumber++;
        this.username = username;
        this.session = session;
//        try {
        //messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
        //先给所有人发送通知，说我上线了
//            Map<String,Object> map1 = Maps.newHashMap();
//            map1.put("messageType",1);
//            map1.put("username",username);
//            try {
//				sendMessageAll(JSON.toJSONString(map1),username);
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}

        //把自己的信息加入到map当中去
        clients.put(username, this);
        System.err.println(username + "上线了");
        for (MyWebSocket item : clients.values()) {
            System.err.println(item.username);
        }
        //给自己发一条消息：告诉自己现在都有谁在线
//            Map<String,Object> map2 = Maps.newHashMap();
//            map2.put("messageType",3);
//            //移除掉自己
//            Set<String> set = clients.keySet();
//            map2.put("onlineUsers",set);
        // sendMessageTo(JSON.toJSONString(map2),username);
        //sendMessageTo();

//        }
//        catch (IOException e){
//        }


        System.err.println("在线人数" + onlineNumber);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        //error.printStackTrace();
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        onlineNumber--;
        //webSockets.remove(this);
        clients.remove(username);
//        try {
        //messageType 1代表上线 2代表下线 3代表在线名单  4代表普通消息
        Map<String, Object> map1 = Maps.newHashMap();
        map1.put("messageType", 2);
        map1.put("onlineUsers", clients.keySet());
        map1.put("username", username);
//            sendMessageAll(JSON.toJSONString(map1),username);
        System.err.println(username + "下线了");
        System.err.println("在线人数" + onlineNumber);

        for (MyWebSocket item : clients.values()) {
            System.err.println(item.username);
        }
//        }
//        catch (IOException e){
//        }
    }

    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        ChatRecordService = applicationContext.getBean(ChatRecordService.class);
        JSONObject jsonObject = JSON.parseObject(message);
        JSONObject jsonObject2 = JSON.parseObject(message);
        jsonObject.put("unreadMsg", 1);
        jsonObject.put("status", "success");
        jsonObject2.put("status", "success");
        JSONObject data = new JSONObject();
        data.put("data", message);
        data.put("code", 0);
        Long sendUserId = Long.parseLong(jsonObject.getString("fromUserId"));
        if (jsonObject.getString("toUserId") == null) {
            System.out.println("onmessage ping: " + sendUserId);
            return;
        }
        Long receiveUserId = Long.parseLong(jsonObject.getString("toUserId"));
        Integer type = 0;//
        String msgType = jsonObject.getString("msgType");
        if (msgType.equals("image")) {
            type = 1;
        }
        if (msgType.equals("voice")) {
            type = 2;
        }
        if (msgType.equals("video")) {
            type = 3;
        }
        if (msgType.equals("location")) {
            type = 4;
        }
        String content = jsonObject.getString("text");
        ChatRecordEntity yActivity1 = new ChatRecordEntity(sendUserId, receiveUserId, null, type, content,
                0, new Date());
        //如果不是发给所有，那么就发给某一个人
        //messageType 1代表上线 2代表下线 3代表在线名单  4代表普通消息
        Map<String, Object> map1 = Maps.newHashMap();
        map1.put("code", 0);
        map1.put("event", "MSG_RECEIVE");
        map1.put("data", jsonObject);
        Map<String, Object> map2 = Maps.newHashMap();
        map2.put("code", 0);
        map2.put("event", "RESPONSE");
        map2.put("data", jsonObject2);
        map1.put("tousername", yActivity1.getReceiveUserId());
        yActivity1.setFileId(1L);
        ChatRecordService.save(yActivity1);
        boolean a = sendMessageTo(JSON.toJSONString(map1), yActivity1.getReceiveUserId().toString());
        if (a == false) {
            int result = JpushClientUtil.sendMessageWithAlias(receiveUserId.toString(), "新消息", "新消息", jsonObject.getString("text"), message);
            System.out.println("极光发送 :" + result);
        }

        sendMessageTo(JSON.toJSONString(map2), yActivity1.getSendUserId().toString());


    }

    public boolean sendMessageTo(String message, String ToUserName) throws IOException {
        boolean result = false;
        for (MyWebSocket item : clients.values()) {
            if (item.username.equals(ToUserName)) {
                item.session.getAsyncRemote().sendText(message);
                System.out.println("websocket :" + message);
                result = true;
                break;
            }
        }
        return result;
    }

    public void sendMessageAll(String message, String FromUserName) throws IOException {
        for (MyWebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineNumber;
    }
}
